﻿using ReceiverNetApi.Repo;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.ServiceProcess;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace ReceiverNetApi.Controllers
{
	[RoutePrefix("api/upload")]
	public class UploadController : ApiController
	{
		[Route("api")]
		public string Get()
		{
			return "success";
		}

		[Route("stopservice")]
		[HttpGet()]
		public string StopServiceApi()
		{
			StopService();
			return "success";
		}

		[Route("startservice")]
		[HttpGet()]
		public string StartServiceApi()
		{
			StartService();
			return "success";
		}

		[Route("api")]
		[HttpPost()]
		public async Task<string> Post([FromUri] string binPath)
		{
			return UploadFile(binPath);
		}

		[Route("service")]
		[HttpPost()]
		public async Task<string> Service([FromUri] string binPath)
		{
			try
			{
				StopService();
				UploadFile(binPath);
				StartService();
				return "success";
			}
			catch (Exception ex)
			{
				return ex.Message;
			}
		}

		private string UploadFile(string binPath)
		{
			var httpRequest = HttpContext.Current.Request;

			if (string.IsNullOrEmpty(binPath))
			{
				return "binPath required";
			}

			foreach (string file in httpRequest.Files)
			{
				var postedFile = httpRequest.Files[file];
				ZipArchive archive = new ZipArchive(postedFile.InputStream);
				archive.ExtractToDirectory(binPath, true);
			}

			return "File uploaded.";
		}

		private const string serviceName = "TFReportScheduler";
		private void StopService()
		{
			ServiceController sc = new ServiceController(serviceName);

			if (sc.Status == ServiceControllerStatus.Running)
			{
				sc.Stop();
				sc.WaitForStatus(ServiceControllerStatus.Stopped);
			}
		}

		private void StartService()
		{
			ServiceController sc = new ServiceController(serviceName);

			if (sc.Status == ServiceControllerStatus.Stopped)
			{
				sc.Start();
				sc.WaitForStatus(ServiceControllerStatus.Running);
			}
		}
	}
}
